package com.zhang.common.batch;


import com.zhang.common.util.StringUtils;
import com.zhang.common.util.object.ReflectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;

import java.lang.reflect.Field;
import java.sql.ResultSet;

/**
 * RowMapper 公共处理
 * SpringBatch Reader 中的 RowMapper 映射
 * 例：setRowMapper(new CommonRowMapper(User.class));
 * @author zhangxin
 * @date 2020-12-21 12:34:00
 */
public class CommonRowMapper<T> implements RowMapper<T> {
    private static final Logger logger = LoggerFactory.getLogger(CommonRowMapper.class);
    private final Class<T> clazz;

    public CommonRowMapper(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public T mapRow(ResultSet rs, int i) {
        try{
            Field[] fields = clazz.getDeclaredFields();
            T t = clazz.getDeclaredConstructor().newInstance();
            for(Field field : fields) {
                Object value = rs.getObject(StringUtils.humpToLine(field.getName()));
                ReflectUtils.invokeSetter(t, field.getName(), value);
            }
            return t;
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e);
        }
        return null;
    }
}
